
import {configKey}  from '../utils';

function strToArray(str: string): string[] {
	let result: any[] = [];
	str.split("").forEach((v, k) => (result[k] = v));
	return result;
}
function filp(arr: string[]): { [p: string]: string } {
	let filpedArr: {
		[p: string]: string;
	} = {};
	Object.keys(arr).forEach(v => (filpedArr[arr[v]] = v));
	return filpedArr;
}

function decrypt(str: string, solution: string) {
	let plain = "";
	const decryptKey = strToArray(solution);
	const filpDecryptKey = filp(decryptKey);
	str.split("").forEach((v, k) => {
		let index = Number(filpDecryptKey[v]) - k;
		while (index <= -1 || index >= configKey.getKey().length + 1) {
			if (index <= -1) {
				index = index + configKey.getKey().length;
			}
			if (index >= configKey.getKey().length + 1) {
				index = index - configKey.getKey().length;
			}
		}
		plain = plain.concat(configKey.getKey()[index]);
	});
	return plain;
}

function decryptUTF8(
	cipher: string,
	solution: string,
	callback?: (err: string, ...args: any[]) => any
): string | undefined {
	try {
		return decodeURI(decrypt(cipher, solution));
	} catch (error) {
		callback && callback(error);
	}
}

export { filp, strToArray, decrypt, decryptUTF8 };
